<?php

namespace Parse;

class RecursiveParser extends Parser
{
    private $root_parser_name;

    public function __construct($root_parser_name, $parser_tree, $callback = null)
    {
        $this->root_parser_name = $root_parser_name;
        $this->parsers = $parser_tree;
        parent::__construct($callback);
        $this->injectParser($this);
    }

    public function defaultCallback()
    {
        return func_get_arg(0);
    }

    private function injectParser($parser)
    {
        foreach ($parser->parsers as $key => &$inner_parser) {
            if (is_string($inner_parser)) {
                if (array_key_exists($inner_parser, $this->parsers)) {
                    $inner_parser = $this->parsers[$inner_parser];
                } else {
                    throw new ParseException(
                        "Parser referenced that does not exist: "
                        . var_dump($inner_parser)
                    );
                }
            } else {
                $this->injectParser($inner_parser);
            }
        }
    }

    public function matchProcedure($string)
    {
        $result = $this->parsers[$this->root_parser_name]->match($string);
        return array(
            "matches" => array($result["match"]),
            "rest" => $result["rest"]);
    }
}
